<template>
  <div>
    <el-dialog
      width="30%"
      :visible.sync="visible"
      title="修改头像"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="个人头像">
          <el-upload
            class="avatar-uploader"
            action="/api/vue-admin-template/user/updatePortrait"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            name="avatar"
          >
            <!-- :http-request="uploadImage" -->
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <div style="color: gray">
          上传图片只能是 JPG/PNG 格式,图片大小不能超过 3MB!
        </div>
        <br>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">修改</el-button>
          <el-button @click="updateInfoClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
import * as api from "@/api/user.js";
import { mapGetters } from "vuex";
import store from "@/store";

export default {
  computed: {
    ...mapGetters(["avatar"]),
  },
  data() {
    return {
      visible: false,

      form: {
        username: "",
        imageUrl: "",
      },
    };
  },

  methods: {
    onSubmit() {
      api
        .updateing(this.form.username, this.form.imageUrl)
        .then((response) => {
          this.$message.success(response.msg);
          this.updateInfoClosed();
          this.$store.commit("user/SET_AVATAR", this.form.imageUrl);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleAvatarSuccess(response) {
      this.form.imageUrl ='https://'+response.data;
      console.log(this.form.imageUrl);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isGIF = file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 1;
      const flag = !isJPG && !isGIF && !isPNG;
      if (flag) {
        this.$message.error("上传头像图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像大小不能超过 1MB!");
      }
      return !flag && isLt2M;
    },
    updateInfoClosed() {
      this.visible = false;
    },
    open(val1, val2) {
      this.form.imageUrl = val1;
      this.form.username = val2;
      this.visible = true;
    },
  },
};
</script>